package br.unisinos.pdm.bluetooth;

import br.unisinos.pdm.GameCanvas;
import br.unisinos.pdm.GameMidlet;
import javax.bluetooth.*;
import javax.microedition.io.*;
import java.io.*;

public class GameServer extends BluetoothConnection implements Runnable{
    
    private StreamConnectionNotifier notifier;
    
    private int initialDiscoverableMode;
    private String url;
    private Thread thread;
    
    public GameServer(GameCanvas gameCanvas){
        super(gameCanvas);
        url = "btspp://localhost:" + GameMidlet.UUID;
    }
    
    public void run() {
        LocalDevice localDevice = null;
        StreamConnection connection = null;
        try{
            localDevice = LocalDevice.getLocalDevice();
            initialDiscoverableMode = localDevice.getDiscoverable();
            localDevice.setDiscoverable(DiscoveryAgent.GIAC); 
            
            notifier = (StreamConnectionNotifier)Connector.open(url);
            connection = notifier.acceptAndOpen();
            
            execute(connection);
        }catch(IOException ex){
            ex.printStackTrace();
        }finally{
            try{
                if(connection != null) connection.close();
                if(notifier != null) notifier.close();
                localDevice.setDiscoverable(initialDiscoverableMode);
            }catch(IOException ex){}
        }        
    }
    
    public void cancel() {
        try{
            if(notifier != null){                
                notifier.close();
                thread = null;
            }
        }catch(Exception ex){}      
    }
    
    public void accept() {
        thread = new Thread(this);
        thread.start();
    }
}
